<template>
  <div class="main-container" style="margin-left: 0px; margin-right: 0px">
    <a-empty v-if="taskList.length <= 0" style="border-radius: 10px; background-color: #fff" />
    <div style="display: flex; flex-wrap: wrap" class="list">
      <div class="box" v-for="item in taskList" :key="item.id">
        <div class="top">
          <div class="name">
            <a-tooltip position="top" :content="item.name">
              <span>
                {{ item.name }}
              </span>
            </a-tooltip>
          </div>
          <div>
            <a-tag v-if="item.execute === false">待执行</a-tag>
            <a-tag v-else-if="item.execute === true" color="arcoblue"> 执行中</a-tag>
            <a-tag v-else color="red">未开始</a-tag>
            <!-- <a-button
                plain
                size="mini"
                type="primary"
                style="margin-left: 10px"
                @click="taskListFnse(item)"
              >
                编辑
              </a-button> -->
          </div>
        </div>
        <div class="center">
          <img src="@/assets/xiazai.png" style="width: 211px; height: 120px" />
        </div>
        <div class="bottom">
          <div v-if="item.list" style="cursor: pointer" @click="taskListFns(item.list)"
            >下次执行：{{ item.list[0] ? item.list[0] : '---' }}</div
          >
          <div v-else
            >成功：{{ item.success }}张 <span>失败：{{ item.error }}张</span>
          </div>
          <div>
            <a-button plain size="mini" :disabled="!item.execute" type="primary" @click="SSE(item)">
              查看
            </a-button>
          </div>
        </div>
      </div>
      <div class="box" v-if="allList.length > 4" @click="open">
        <div class="top" style="border-bottom: 0"> </div>
        <div class="center">
          <img
            v-if="showList == true"
            src="@/assets/guan.png"
            style="width: 120px; height: 120px"
            alt=""
          />
          <img v-else src="@/assets/lun.png" style="width: 120px; height: 120px" alt="" />
          <div style="width: 100%; text-align: center; margin-top: 10px">{{
            showList == true ? '收起' : '展开更多轮询......'
          }}</div>
        </div>
        <div class="bottom" style="border-top: 0"> </div>
      </div>
    </div>
    <!--轮询任务 -->
    <a-modal
      v-model:visible="showse"
      width="800px"
      :mask-closable="false"
      title-align="start"
      @before-close="close"
    >
      <template #title>
        {{ forms.name }}
      </template>
      <div class="alert">
        <div style="color: #fff">
          轮询数据： 成功数量：{{ forms.success }}张 失败数量：{{ forms.error }}张 成功率：{{
            Math.floor((forms.success / (forms.error + forms.success)) * 100)
          }}%
        </div>
        <icon-sync v-if="showSuccess == false" :style="{ fontSize: '15px' }" spin />
        <div v-else style="color: #fff">轮询完成</div>
      </div>
      <div> <a-divider dashed>实时数据</a-divider> </div>
      <div
        :class="top == -1 ? 'mail-container yin' : top >= 0 ? 'mail-container yin1' : ''"
        ref="scrollWrapperRef"
        @scroll="handleScroll"
        style="height: 500px; overflow-y: auto"
      >
        <div v-for="item in dataList" :key="item">
          {{ item }}
        </div>
      </div>
      <template #footer>
        <a-space />
      </template>
    </a-modal>
    <!--时间 -->
    <a-modal
      v-model:visible="dates"
      title="近24小时执行时间"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <div style="height: 500px; overflow-y: auto">
        <div v-for="item in list" :key="item">
          {{ item }}
        </div>
      </div>
      <template #footer>
        <a-space />
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { tasklist } from '@/api/url'
  import { onMounted, onUnmounted, ref } from 'vue'
  import { get } from '@/api/http'
  import { Message } from '@arco-design/web-vue'
  const taskList: any = ref([])
  const showse = ref(false)
  const showsa = ref(false)
  const dataList: any = ref([])
  const showList = ref(false)
  const allList: any = ref([])
  const activeList: any = ref([])
  const forms: any = ref({})
  const time = ref()
  const top = ref(0)

  const scrollWrapperRef = ref() //滚动区域的父元素
  const handleScroll = () => {
    //滚动触发的事件
    const scrollWrapper = scrollWrapperRef.value // 获取滚动容器
    const { scrollTop, clientHeight, scrollHeight } = scrollWrapper // 获取滚动数据
    // console.log('scrollWrapper', scrollTop, clientHeight, scrollHeight)
    // 判断是否滚动到底部
    if (scrollTop == 0) {
      top.value = scrollTop
    } else if (scrollTop + clientHeight >= scrollHeight - 10) {
      top.value = -1
    }
  }
  function taskListFn() {
    get({
      url: tasklist,
      data: {},
    })
      .then((res) => {
        if (res.code == 0) {
          taskList.value = []
          activeList.value = []
          res.data.forEach((item: any, index: any) => {
            if (item.execute == true && activeList.value.length < 5) {
              activeList.value.push(item)
            }
            if (item.id == forms.value.id) {
              if (item.execute != true) {
                showSuccess.value = true
              }
            }
          })
          allList.value = res.data
          if (showList.value == true) {
            taskList.value = res.data
          } else {
            if (activeList.value.length > 0) {
              taskList.value = activeList.value
            } else {
              res.data.forEach((item: any, index: any) => {
                if (index <= 3) {
                  taskList.value.push(item)
                }
              })
            }
          }

          // taskList.value = res.data
        }
      })
      .catch(console.log)
  }

  function open() {
    showList.value = !showList.value
    taskList.value = []
    if (showList.value == true) {
      taskList.value = allList.value
    } else {
      if (activeList.value.length > 0) {
        taskList.value = activeList.value
      } else {
        allList.value.forEach((item: any, index: any) => {
          if (index <= 3) {
            taskList.value.push(item)
          }
        })
      }
    }
  }

  const list = ref([])
  const ast = ref(false)
  const dates = ref(false)
  const renewForm: any = ref({})
  function taskListFns(val: any) {
    list.value = val
    dates.value = true
  }

  function close() {
    ast.value = false
    showsa.value = false
    dataList.value = []
    clearInterval(time.value)
    source.value.close()
    showse.value = false
    console.log(111)
  }
  const source = ref()
  const showSuccess = ref(false)
  const SSE = (val: any) => {
    forms.value = val
    showSuccess.value = false
    if (window.EventSource) {
      if (showsa.value == true) {
      } else {
        showsa.value = true
        // 建立连接
        source.value = new EventSource('/app/polling/task/get/message?id=' + val.id)
        /**
         * 连接一旦建立，就会触发open事件
         */

        source.value.onopen = function (e: any) {
          console.log('建立连接', e)
        }
        /**
         * 客户端收到服务器发来的数据
         */
        source.value.onmessage = function (e: any) {
          showse.value = true
          if (dataList.value.length < 1000) {
            dataList.value.unshift(e.data)
          } else {
            dataList.value.unshift(e.data)
            dataList.value.pop()
          }
        }
        /**
         * 如果发生通信错误（比如连接中断），就会触发error事件
         */
        source.value.onerror = function (e: any) {
          showsa.value = false
          if (e.readyState === EventSource.CLOSED) {
            console.log('连接关闭')
          } else {
            Message.error('超时请重试')
            renewForm.value = {}
            showse.value = false
            source.value.close()
          }
        }
      }
    } else {
      console.log('浏览器不支持SSE')
    }
    time.value = setInterval(() => {
      setTimeout(() => {
        taskList.value.forEach((item: any) => {
          if (forms.value.id == item.id) {
            forms.value = item
          }
        })
      }, 0)
    }, 3000)
  }

  let aas: any = null
  onMounted(() => {
    taskListFn()
    aas = window.setInterval(() => {
      setTimeout(() => {
        taskListFn()
      }, 0)
    }, 3000)
  })

  onUnmounted(() => {
    clearInterval(aas)
    console.log('销毁')
  })
</script>

<style lang="less" scoped>
  .yin {
    box-shadow: 0px 10px 10px -8px #0000001a inset;
  }
  .yin1 {
    box-shadow: 0px -10px 10px -8px #0000001a inset;
  }
  .alert {
    display: flex;
    justify-content: space-between;
    color: #fff;
    padding: 10px;
    border-radius: 5px;
    align-items: center;
    background: linear-gradient(110deg, #3491fa, #7bc0fc);
  }
  ::-webkit-scrollbar {
    width: 3px;
    height: 0.75rem;
    background-color: #f5f5f5;
  }
  // :deep(.arco-divider-text) {
  //   background: transparent !important;
  // }
  .main-container {
  }
  .box {
    width: calc(20% - 20px);
    background: #fff;
    border: 1px solid #ededed;
    margin-bottom: 20px;
    margin-left: 20px;
    height: 268px;

    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      height: 50px;
      border-bottom: 1px solid #ededed;
      .name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .center {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
      flex-wrap: wrap;
    }
    .bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 50px;
      border-top: 1px solid #ededed;
      padding: 20px;
    }
  }

  .list {
    width: calc(100% - 20px);
  }
</style>
